package cn.wolfcode.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.wolfcode.utils.UploadUtil;

@Controller
public class MainController {

	@Value("${file.path}")
	private String filePath;

	/**
	 * 后台管理界面首页
	 */
	@RequestMapping(value = "/main")
	public String main() {
		return "main";
	}

	@RequestMapping(value = "/")
	public String root() {
		return "forward:/main";
	}

	/**
	 * 首页的内容
	 */
	@RequestMapping(value = "/index")
	public String index() {
		return "index";
	}

	/**
	 * 上传图片
	 * 
	 * @param img
	 * @return
	 */
	@RequestMapping(value = "/uploadImage")
	@ResponseBody
	public String uploadImage(MultipartFile image) {
		String fileName = UploadUtil.upload(image, filePath);
		return "/" + fileName;
	}

	/**
	 *
	 * @param upload   ckedit默认找upload变量名
	 * @param request  ckedit上传图片需要用到
	 * @param response ckedit上传图片需要用到
	 */
	@RequestMapping(value = "/ckeditUploadImg")
	public void ckeditUploadImg(MultipartFile upload, HttpServletRequest request, HttpServletResponse response) {
		try {
			// 上传文件并返回文件名
			String fileName = UploadUtil.upload(upload, filePath);
			// 结合ckeditor功能
			// imageContextPath为图片在服务器地址，如/123.jpg,非绝对路径
			String imageContextPath = "/" + fileName;
			response.setContentType("text/html;charset=UTF-8");
			String callback = request.getParameter("CKEditorFuncNum");
			PrintWriter out = response.getWriter();
			out.println("<script type=\"text/javascript\">");
			out.println(
					"window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageContextPath + "',''" + ")");
			out.println("</script>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
